package com.lm.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.alibaba.fastjson.serializer.ValueFilter;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 10:38 2024/5/10
 */
public class FastJsonTest {
    //将 JSONObject 对象序列化为 JSON 字符串。
    public static void toJSONStringExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "John");
        jsonObject.put("age", 30);

        String jsonString = jsonObject.toJSONString();
        System.out.println(jsonString);
    }

    //将 JSON 字符串解析为 JSONObject 对象。
    public static void parseObjectExample() {
        String json = "{\"name\":\"Alice\",\"other\":{\"adress\":\"wuhan\",\"age\":\"25\"}}";
        //{&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:25}
        //String json = "{&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:25}";
        JSONObject jsonObject = JSON.parseObject(json);
        jsonObject.forEach((k,v)->{

        });
        String name = jsonObject.getString("name");
        JSONObject age = jsonObject.getJSONObject("age");

        System.out.println("Name: " + name + ", Age: " + age);
    }


    //将 JSON 数组字符串解析为 Java 数组。
    public static void parseArrayExample() {
        String jsonArray = "[1, 2, 3, 4, 5]";
        JSONArray intArray = JSON.parseArray(jsonArray);

        int sum = 0;
        for (Object num : intArray) {
            sum += (int) num;
        }
        System.out.println("Sum: " + sum);
    }

    public static class Person {
        public String name;
        public int age;
    }

    //将 JSON串 转换为指定类型的 Java 对象。
    public static void toJavaObjectExample() {
        String json = "{\"name\":\"Bob\",\"age\":28,\"arr\":[{\"address\":\"北京\",\"date\":\"20200809\"},{\"address\":\"武汉\",\"date\":\"20200909\"},{\"address\":\"上海\",\"date\":\"20200809\"}]}";
        JSONObject object = JSON.parseObject(json);
        JSONArray arr = object.getJSONArray("arr");
//        for (Object o : arr) {
//            if (o instanceof JSONObject) {
//                ((JSONObject)o).forEach((k,v)-> System.out.println(v));
//            }
//        }
        //Person person = JSON.toJavaObject(object, Person.class);

        //System.out.println("Name: " + person.name + ", Age: " + person.age);

        Map<String, List<Object>> listMap = arr.stream().collect(Collectors.groupingBy((var) -> ((JSONObject) var).getString("date"), Collectors.toList()));
        Set<Map.Entry<String, List<Object>>> entries = listMap.entrySet();
        for (Map.Entry<String, List<Object>> entry : entries) {
            System.out.println(entry.getKey());
            List<Object> list = entry.getValue();
            for (Object o : list) {
                if (o instanceof JSONObject) {
                    ((JSONObject)o).forEach((k,v)-> System.out.println(v));
                }
            }
        }
    }

    //将 Java 对象序列化为 JSON 字节数组。
    public static void toJSONBytesExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Charlie");
        jsonObject.put("age", 35);

        byte[] jsonBytes = JSON.toJSONBytes(jsonObject);
        String jsonString = new String(jsonBytes);
        System.out.println(jsonString);
    }

    //使用指定日期格式将 Java 对象序列化为 JSON 字符串。
    public static void toJSONStringWithDateFormatExample() {
        Date today = new Date();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "David");
        jsonObject.put("birthDate", today);
        //带格式  {"name":"David","birthDate":"2024-05-10"}
        System.out.println(JSON.toJSONStringWithDateFormat(jsonObject, "yyyy-MM-dd"));
        //不带格式 {"name":"David","birthDate":1715309544541}
        System.out.println(jsonObject.toJSONString());
    }

    //使用过滤器将 Java 对象序列化为 JSON 字符串
    public static void toJSONStringWithFilterExample() {
        Person person = new Person();
        person.name = "Eve";
        person.age = 40;

        ValueFilter filter = (object, name, value) -> {
            if (name.equals("age")) {
                return null; // 不包括 "age" 字段
            }
            return value;
        };

        String jsonString = JSON.toJSONString(person, filter);
        System.out.println(jsonString);
    }

    //parse()：将 JSON 字符串解析为通用的 java.lang.Object 对象。
    public static void parseExample() {
        String json = "{\"name\":\"Frank\",\"age\":45}";
        Object object = JSON.parse(json);

        if (object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            String name = jsonObject.getString("name");
            int age = jsonObject.getIntValue("age");

            System.out.println("Name: " + name + ", Age: " + age);
        }
    }

    //isValid()：检查 JSON 字符串是否合法。
    public static void isValidExample() {
        String validJson = "{\"name\":\"Grace\",\"age\":50}";
        String invalidJson = "{name\":\"Helen\",\"age\":55}";

        //  boolean valid = JSON.isValid(validJson);
        // boolean invalid = JSON.isValid(invalidJson);
        boolean valid = JSONValidator.from(validJson).validate();
        boolean invalid = JSONValidator.from(invalidJson).validate();

        System.out.println("Valid JSON: " + valid);
        System.out.println("Invalid JSON: " + invalid);
    }

    //getJSONObject()：获取 JSON 对象中的子对象。
    public static void getJSONObjectExample() {
        String json = "{\"person\":{\"name\":\"Ivy\",\"age\":60}}";
        JSONObject jsonObject = JSON.parseObject(json);

        JSONObject personObject = jsonObject.getJSONObject("person");
        String name = personObject.getString("name");

        System.out.println("Name: " + name);
    }


    //getJSONArray()：获取 JSON 对象中的子数组。
    public static void getJSONArrayExample() {
        String json = "{\"numbers\":[1, 2, 3, 4, 5]}";
        JSONObject jsonObject = JSON.parseObject(json);

        JSONArray numbersArray = jsonObject.getJSONArray("numbers");
        int sum = 0;

        for (Object num : numbersArray) {
            sum += (int) num;
        }

        System.out.println("Sum: " + sum);
    }

    //合并两个json对象
    public static void mergeExample() {
        String json1 = "{\"name\":\"Jack\"}";
        String json2 = "{\"age\":35}";

        JSONObject jsonObject1 = JSON.parseObject(json1);
        JSONObject jsonObject2 = JSON.parseObject(json2);

        jsonObject1.putAll(jsonObject2);
        System.out.println(jsonObject1.toJSONString());
    }


    //containsValue(Object value): 检查 JSON 对象是否包含指定的值
    public static void containsValueExample() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "Bob");
        jsonObject.put("age", 35);

        boolean containsName = jsonObject.containsValue("Bob");
        boolean containsGender = jsonObject.containsValue("Male");

        System.out.println("Contains Name: " + containsName);
        System.out.println("Contains Gender: " + containsGender);
    }

    //对象list解析为JSONArray
    public static void parseListExample() {
        String listString = "[{\"amt\":100000.0,\"date\":\"2022-07-22\",\"id\":5,\"num\":\"s3\",\"status\":\"1\"},{\"amt\":500000.0,\"date\":\"2023-09-15\",\"id\":6,\"num\":\"s3\",\"status\":\"1\"},{\"amt\":20000.0,\"date\":\"2020-11-11\",\"id\":8,\"num\":\"s4\",\"status\":\"1\"},{\"amt\":1000000.0,\"date\":\"2021-11-13\",\"id\":8,\"num\":\"s5\",\"status\":\"1\"},{\"amt\":200000.0,\"date\":\"2021-03-04\",\"id\":2,\"num\":\"s1\",\"status\":\"1\"}]";
        JSONArray objects = JSON.parseArray(listString);
//        for (Object object : objects) {
//            System.out.println(object);
//            System.out.println(object.getClass());
//        }
        Map<Object, List<Object>> listMap = objects.stream().collect(Collectors.groupingBy(js -> ((JSONObject) js).getString("date")));
        Optional<Map.Entry<Object, List<Object>>> first = listMap.entrySet().stream().findFirst();
        first.get().getValue().forEach(System.out::println);
    }


    public static void main(String[] args) {
        parseListExample();
    }


}
